<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="450px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
        <el-form-item label="角色名称" prop="role_name">
          <el-input
            class="input_style"
            v-model="formData.role_name"
            clearable
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item label="角色标识" prop="identify">
          <el-input
            class="input_style"
            v-model="formData.identify"
            clearable
            placeholder="请输入角色的标识"
          />
        </el-form-item>
        <el-scrollbar>
          <el-form-item label="角色权限" prop="menu_id">
            <el-checkbox
              v-model="isExpand"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <br />
            <div class="flex" style="width: 100%">
              <el-checkbox-group v-model="formData.menu_id" @change="handleCheckedCitiesChange">
                <!--
                  
                  :value="item.id"
                -->
                <el-checkbox
                  v-for="item in permissionLists"
                  :key="item.id"
                  :label="item.id"
                >{{ item.permission_name }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-scrollbar>
        <el-form-item label="角色备注" prop="remark">
          <el-input class="input_style" v-model="formData.remark" clearable placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input class="input_style" v-model="formData.sort" clearable placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="formData.status" placeholder="请选择状态">
            <el-radio
              v-for="(item, index) in dictData.status"
              :key="index"
              :label="parseInt(item.value)"
            >{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>

<script lang="ts" setup name="memberRolesEdit">
import type { CheckboxValueType, ElTree, FormInstance } from "element-plus"
import { ref, watch } from "vue"
import Popup from "@/components/popup/index.vue"
import {
  apiMemberRolesAdd,
  apiMemberRolesEdit,
  apiMemberRolesDetail,
} from "@/api/member_roles"
import { timeFormat } from "@/utils/util"
import type { PropType } from "vue"
defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({}),
  },
})

const emit = defineEmits(["success", "close"])
const mode = ref("add")
import { treeToArray } from "@/utils/util"
import { menuAll } from "@/api/perms/menu"
const treeRef = shallowRef<InstanceType<typeof ElTree>>()
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const isExpand = ref(false) //全选
const isIndeterminate = ref(false) //是否有选中的状态
const permissionLists = ref([]) //列表
//查询用户权限
import { apiMemberPermissionsLists } from "@/api/member_permissions"
const queryParamsONE = reactive({
  permission_name: "",
})
const getpermissionLists = async () => {
  const res = await apiMemberPermissionsLists(queryParamsONE)
  permissionLists.value = res.lists
}
getpermissionLists()

// 表单数据
const formData = reactive({
  id: "",
  role_name: "",
  identify: "",
  remark: "",
  sort: "",
  status: "",
  menu_id: [],
})
//  角色选择
const handleCheckAllChange = (val: boolean) => {
  if (val) {
    formData.menu_id = permissionLists.value.map((item: any) => {
      return item.id
    })
  } else {
    formData.menu_id = []
  }
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  isExpand.value = checkedCount === permissionLists.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < permissionLists.value.length
}
// 表单验证
const formRules = reactive<any>({
  role_name: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: ["blur"],
    },
  ],
  identify: [
    {
      required: true,
      message: "请输入角色的标识",
      trigger: ["blur"],
    },
  ],
  status: [
    {
      required: true,
      message: "请选择状态",
      trigger: ["blur"],
    },
  ],
  menu_id: [
    {
      type: "array",
      required: true,
      message: "请选择角色权限",
      trigger: "change",
    },
  ],
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
  const checkedCount = data.menu_id.length
  isExpand.value = checkedCount === data.menu_id.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < data.menu_id.length
}

const getDetail = async (row: Record<string, any>) => {
  const data = await apiMemberRolesDetail({
    id: row.id,
  })
  setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
  await formRef.value?.validate()
  const data = { ...formData }
  mode.value == "edit"
    ? await apiMemberRolesEdit(data)
    : await apiMemberRolesAdd(data)
  popupRef.value?.close()
  emit("success")
}

//打开弹窗
const open = (type = "add") => {
  mode.value = type
  popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
  emit("close")
}

defineExpose({
  open,
  setFormData,
  getDetail,
})
</script>
<style lang="scss" scoped>
.block_checkbox {
  width: 100%;
}

.inline_block {
  display: flex;
  font-weight: bold;
  flex-wrap: wrap;

  .eachCheck {
    width: 100%;
  }
}
</style>
